﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Xml;
using System.IO;

public partial class weixin : System.Web.UI.Page
{
    const string Token = "jinhuan";//你的token

    protected void Page_Load(object sender, EventArgs e)
    {

        string postStr = "";

        if (Request.HttpMethod.ToLower() == "post")
        {

            System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;

            byte[] b = new byte[s.Length];

            s.Read(b, 0, (int)s.Length);

            postStr = System.Text.Encoding.UTF8.GetString(b);

            if (!string.IsNullOrEmpty(postStr))
            {

                //ResponseMsg(postStr);

                Response.Write(ResponseMsg(postStr));

                Response.End();

            }

            //WriteLog("postStr:" + postStr);

        }

        else
        {

            Valid();

        }

    }

    /// <summary>

    /// 验证微信签名

    /// </summary>

    /// * 将token、timestamp、nonce三个参数进行字典序排序

    /// * 将三个参数字符串拼接成一个字符串进行sha1加密

    /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。

    /// <returns></returns>

    private bool CheckSignature()
    {

        string signature = "";
        if (Request.QueryString["signature"] != null)
        {
            signature = Request.QueryString["signature"].ToString();
        }


        string timestamp = "";
        if (Request.QueryString["timestamp"] != null)
        {
            timestamp = Request.QueryString["timestamp"].ToString();
        }


        string nonce = "";
        if (Request.QueryString["nonce"] != null)
        {
            nonce = Request.QueryString["nonce"].ToString();
        }


        string[] ArrTmp = { Token, timestamp, nonce };

        Array.Sort(ArrTmp);     //字典排序

        string tmpStr = string.Join("", ArrTmp);

        tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");

        tmpStr = tmpStr.ToLower();

        if (tmpStr == signature)
        {

            return true;

        }

        else
        {

            return false;

        }

    }

    private void Valid()
    {

        string echoStr = "";
        if (Request.QueryString["echoStr"] != null)
        {
            echoStr = Request.QueryString["echoStr"].ToString();
        }


        if (CheckSignature())
        {

            if (!string.IsNullOrEmpty(echoStr))
            {

                Response.Write(echoStr);

                Response.End();

            }

        }

    }

    /// <summary>

    /// 返回信息结果(微信信息返回)

    /// </summary>

    /// <param name="weixinXML"></param>

    private string ResponseMsg(string weixinXML)
    {

        string resxml = "";

        XmlDocument doc = new XmlDocument();

        doc.LoadXml(weixinXML);

        XmlElement rootElement = doc.DocumentElement;

        XmlNode MsgType = rootElement.SelectSingleNode("MsgType");

        //RequestXML requestXML = new RequestXML();

        string ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;

        string FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;

        string CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;

        string MsgType1 = MsgType.InnerText;

        if (MsgType1 == "text")
        {

            string Content = rootElement.SelectSingleNode("Content").InnerText;

            //if (Content.Trim() == "2")
            //{

            //    resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[茂名好味道正在建设中......]]></Content></xml>";

            //}

            //else if (Content.Trim() == "一战到底")
            //{

            //    string url = "http://www.你的域名.com/wx_yzdd.aspx?name=" + FromUserName;

            //    resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[news]]></MsgType><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[一站到底]]></Title><Description><![CDATA[测试版]]></Description><PicUrl><![CDATA[http://www.你的域名.com/image/wx_yzdd.jpg]]></PicUrl><Url><![CDATA[" + url + "]]></Url></item></Articles></xml>";

            //}

            //else
            //{

            //    resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[茂名好味道正在建设中......]]></Content></xml>";

            //}
            mydata mydatacon = new mydata();
            
            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[" + mydatacon.ChaXun(Content) + "]]></Content></xml>";

            System.Web.HttpContext.Current.Response.Write(resxml);

            return resxml;

        }

        else
        {

            resxml = "<xml><ToUserName><![CDATA[" + FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + ToUserName + "]]></FromUserName><CreateTime>" + ConvertDateTimeInt(DateTime.Now) + "</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[欢迎关注哦]]></Content></xml>";

            System.Web.HttpContext.Current.Response.Write(resxml);

            return resxml;

        }

    }

    /// <summary>

    /// unix时间转换为datetime

    /// </summary>

    /// <param name="timeStamp"></param>

    /// <returns></returns>

    private DateTime UnixTimeToTime(string timeStamp)
    {

        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));

        long lTime = long.Parse(timeStamp + "0000000");

        TimeSpan toNow = new TimeSpan(lTime);

        return dtStart.Add(toNow);

    }

    /// <summary>

    /// datetime转换为unixtime

    /// </summary>

    /// <param name="time"></param>

    /// <returns></returns>

    private int ConvertDateTimeInt(System.DateTime time)
    {

        System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));

        return (int)(time - startTime).TotalSeconds;

    }

    /// <summary>

    /// 写日志(用于跟踪)

    /// </summary>

    private void WriteLog(string strMemo)
    {

        string filename = Server.MapPath("/logs/log.txt");

        if (!Directory.Exists(Server.MapPath("//logs//")))

            Directory.CreateDirectory("//logs//");

        StreamWriter sr = null;

        try
        {

            if (!File.Exists(filename))
            {

                sr = File.CreateText(filename);

            }

            else
            {

                sr = File.AppendText(filename);

            }

            sr.WriteLine(strMemo);

        }

        catch
        {

        }

        finally
        {

            if (sr != null)

                sr.Close();

        }

    }
}